响应式 Props 解构

在 Vue 3.5 及以上版本中,从 defineProps 返回值解构出的变量是响应式的

ts
const { foo } = defineProps(['foo'])

watchEffect(() => {
  // 在 3.5 之前仅运行一次
  // 在 3.5+ 版本中会在 "foo" prop 改变时重新运行
  console.log(foo)
})

当在同一个 <script setup> 块中的代码访问从 defineProps 解构出的变量时,Vue 的编译器会自动在前面添加 props.

ts
const props = defineProps(['foo'])

watchEffect(() => {
  // `foo` 由编译器转换为 `props.foo`
  console.log(props.foo)
})

声明默认值

3.4 及以下

ts
interface Props {
  labels?: string[]
  msg?: string
}

const props = withDefaults(defineProps<Props>(), {
  labels: () => ['one', 'two'], // 注意要使用函数
  msg: 'hello'
})

3.5 及以上

ts
interface Props {
  labels?: string[]
  msg?: string
}

const { labels = ['one', 'two'], msg = 'hello' } = defineProps<Props>()